package com.sh.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerExceptionResolver;

import com.sh.exception.CustomException;
import com.sh.util.ConstantUtil;
import com.sh.util.JwtUtil;

/**
 * 过滤权限
 * */
@WebFilter(filterName="jwtFilter",urlPatterns="/api/*")
public class AuthorizeFilter implements Filter {

	//JWT私钥
	@Value("${jwt.private.key}")
	private String JWT_PRIVATE_KEY = "default";

	@Autowired
	@Qualifier("handlerExceptionResolver")
	private HandlerExceptionResolver resolver;

	//白名单
	private List<String> whiteList = new ArrayList<String>();

	@Override
	public void init(FilterConfig init) throws ServletException {
		whiteList.add("login");

	}

	@Override
	public void doFilter(ServletRequest request,
						 ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		//过滤掉白名单
		String servletPath = httpRequest.getServletPath();
		String requestUrl = "";	//访问的具体路径
		if(!StringUtils.isEmpty(servletPath)){
			String[] split = servletPath.split("/");
			requestUrl = split[split.length-1];
		}
		if(whiteList.contains(requestUrl)){
			chain.doFilter(request, response);
			return;
		}

		//拿取过滤头部
		String token = httpRequest.getHeader("Authorization");
		if(!StringUtils.isEmpty(token)) {
			String username = JwtUtil.getUsername(token);

			boolean verify =
					JwtUtil.verify(token, username, JWT_PRIVATE_KEY);
			if(verify){
				request.setAttribute("loginUserName", username);
				chain.doFilter(request, response);
				return;
			}
		}
		// token 校验失败，抛出异常
		resolver.resolveException(
				(HttpServletRequest)request,
				(HttpServletResponse)response,
				null, new CustomException(ConstantUtil.LOGIN_EXPIRED));

	}

}
